(function () {
  var checkAll = document.getElementById("checkAll");
  var tbody = document.querySelector("tbody");
  var checks = document.querySelectorAll("td input");
  var ths = document.querySelectorAll("th");
  var trs = document.querySelectorAll("tbody tr");
  var init = function () {
    initEvents(); //事件调用
  };

  // 绑定事件函数，
  var initEvents = function () {
    checkAll.addEventListener("click", onCheckAllClick);
    tbody.addEventListener("click", onTbodyClick);
    for (var i = 1; i < ths.length; i++) {
      (function (i) {
        handleThsClickFn(ths[i], i);
      })(i);
    }
  };

  var onCheckAllClick = function () {
    // 获取dom 节点的选中状态
    var checkStatus = this.checked;
    for (var i = 0; i < checks.length; i++) {
      checks[i].checked = checkStatus;
    }
  };

  var onTbodyClick = function (e) {
    if (e.target.tagName !== "INPUT") {
      return;
    }
    var checkedNum = 0;
    for (var i = 0; i < checks.length; i++) {
      console.log(checks[i].checked);
      if (checks[i].checked) {
        checkedNum++;
      }
    }
    checkAll.checked = checkedNum === checks.length;
  };

  var handleThsClickFn = function (th, index) {
    th.addEventListener("click", function () {
      var arr = Array.prototype.slice.call(trs).sort((a, b) => {
        if (index === 2 || index === 4) {
          return a.children[1].innerHTML.localeCompare(b.children[1].innerHTML, 'zh')
        }
        return a.children[1].innerHTML - b.children[1].innerHTML;
      });
      for (var i = 0; i < arr.length; i++) {
        tbody.appendChild(arr[i]);
      }
    });
  };
  init();
})();
